#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
应用程序框架分析器 - 任务处理器
处理分析任务的异步执行
"""

import json
import traceback
import os
import shutil
from pathlib import Path
from datetime import datetime

from src.core.analyzer import AppAnalyzer
from .app import tasks
from .config import UPLOAD_FOLDER, AUTO_CLEANUP_UPLOADS


def analyze_task(task_id: str, file_path: Path, platform: str, report_folder: Path):
    """
    异步执行分析任务
    
    Args:
        task_id: 任务ID
        file_path: 应用文件路径
        platform: 平台类型（或auto自动检测）
        report_folder: 报告输出目录
    """
    try:
        # 更新任务状态
        tasks[task_id]['status'] = 'processing'
        tasks[task_id]['updated_at'] = datetime.now().isoformat()
        
        # 创建输出目录
        output_path = Path(report_folder) / task_id
        output_path.mkdir(parents=True, exist_ok=True)
        
        # 执行分析
        analyzer = AppAnalyzer(
            app_path=file_path,
            platform=platform,
            output_path=output_path,
            verbose=True
        )
        
        result = analyzer.analyze()
        
        # 将结果保存为JSON文件
        result_json_path = output_path / 'result.json'
        with open(result_json_path, 'w', encoding='utf-8') as f:
            json.dump(result.to_dict(), f, ensure_ascii=False, indent=2)
        
        # 更新任务状态
        tasks[task_id]['status'] = 'completed'
        
        # 将信心值转换为百分比值(0-100)
        for fw in result.frameworks:
            if isinstance(fw.confidence, float) and 0 <= fw.confidence <= 1:
                fw.confidence = int(fw.confidence * 100)
        
        tasks[task_id]['result'] = {
            'summary': result.summary(),
            'frameworks': [fw.to_dict() for fw in result.frameworks],
            'report_path': str(output_path),
            'result_json': str(result_json_path)
        }
        
        # 分析完成后，如果配置为自动清理，则清理上传的安装包文件
        if AUTO_CLEANUP_UPLOADS:
            cleanup_upload_files(task_id)
        
    except Exception as e:
        error_msg = str(e)
        error_trace = traceback.format_exc()
        
        # 更新任务状态为失败
        tasks[task_id]['status'] = 'failed'
        tasks[task_id]['error'] = {
            'message': error_msg,
            'traceback': error_trace
        }
        
        # 记录错误日志
        print(f"分析任务 {task_id} 失败: {error_msg}")
        print(error_trace)
        
        # 即使分析失败，如果配置为自动清理，也清理上传的安装包文件
        if AUTO_CLEANUP_UPLOADS:
            cleanup_upload_files(task_id)
    
    finally:
        # 更新任务最后更新时间
        tasks[task_id]['updated_at'] = datetime.now().isoformat()


def cleanup_upload_files(task_id: str):
    """
    清理指定任务的上传文件
    
    Args:
        task_id: 任务ID
    """
    try:
        upload_dir = Path(UPLOAD_FOLDER) / task_id
        if upload_dir.exists():
            print(f"清理任务 {task_id} 的上传文件...")
            shutil.rmtree(upload_dir)
            print(f"任务 {task_id} 的上传文件已清理")
            
            # 更新任务记录，标记为已清理
            if task_id in tasks:
                tasks[task_id]['upload_cleaned'] = True
    except Exception as e:
        print(f"清理上传文件时出错: {e}")
        traceback.print_exc() 
